package com.esbi.projectwebsocket.threadLocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadLocalExample001 {


    // 创建一个 ThreadLocal 变量，用于存储每个线程的独立值
    private static ThreadLocal<Integer> threadLocalValue = new ThreadLocal<Integer>() {
        // 覆盖 initialValue 方法，设置初始值
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    public static void main(String[] args) {
        // 创建一个线程池来管理线程
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // 提交多个任务到线程池中
        for (int i = 0; i < 5; i++) {
            executorService.submit(new Task(i));
        }

        // 关闭线程池
        executorService.shutdown();
    }

    // 定义一个任务类，每个任务都会在其线程中运行
    static class Task implements Runnable {
        private int taskId;

        public Task(int taskId) {
            this.taskId = taskId;
        }

        @Override
        public void run() {
            // 打印当前线程的名称
            System.out.println("Thread: " + Thread.currentThread().getName());

            // 获取当前线程的 ThreadLocal 变量，并增加其值
            Integer currentValue = threadLocalValue.get();
            currentValue += 1;
            threadLocalValue.set(currentValue);

            // 打印 ThreadLocal 变量的值
            System.out.println("Task ID: " + taskId + ", ThreadLocal Value: " + threadLocalValue.get());

            // 尝试获取其他线程（假设存在）的 ThreadLocal 值（实际上这是不可能的，因为 ThreadLocal 是线程隔离的）
            // 这里的注释只是为了强调 ThreadLocal 的线程隔离特性
            // System.out.println("Trying to access another thread's ThreadLocal value (hypothetically): " + someOtherThreadLocalValue);

            // 休眠一段时间，模拟任务执行时间
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 再次打印 ThreadLocal 变量的值，验证其线程隔离性
            System.out.println("Task ID: " + taskId + ", ThreadLocal Value after sleep: " + threadLocalValue.get());
        }
    }
}